package br.eng.eliseu.gwt.aconchego.camera.client.ui;


import br.eng.eliseu.gwt.aconchego.camera.client.service.LoginService;
import br.eng.eliseu.gwt.aconchego.camera.client.service.LoginServiceAsync;
import br.eng.eliseu.gwt.aconchego.camera.module.AcessoCam;
import br.eng.eliseu.gwt.aconchego.camera.module.Camera;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class VideoView extends Composite {

	interface VideoViewUiBinder extends UiBinder<Widget, VideoView> {}
	private static VideoViewUiBinder uiBinder = GWT.create(VideoViewUiBinder.class);
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);
	
	@UiField VerticalPanel videoViewPanel;
	@UiField Label nomeCameraLabel;
	@UiField Label nomeUsuarioLabel;
	@UiField Label intervaloLabel;
	@UiField Label msgErroLabel;
	@UiField ListBox cameras1CBox;
	@UiField HTMLPanel video1Panel;
	@UiField ListBox cameras2CBox;
	@UiField HTMLPanel video2Panel;

	private AcessoCam usuarioLogin;

	/**
	 * @param usuarioLogin
	 */
	public VideoView( AcessoCam usuarioLogin) {
		initWidget(uiBinder.createAndBindUi(this));

		this.setUsuarioLogin(usuarioLogin);

		DateTimeFormat fmtHora = DateTimeFormat.getFormat("HH:mm");
		nomeUsuarioLabel.setText(usuarioLogin.getUsuario().getNome());
		if (usuarioLogin.getPeriodoInicio()==null){
			intervaloLabel.setText("livre");
		} else {
			intervaloLabel.setText(fmtHora.format(usuarioLogin.getPeriodoInicio()) + " as " + fmtHora.format(usuarioLogin.getPeriodoFim()));
		}
		populaListCameras();
//		drawVideo();
		iniciaChecagemDoTempos();

	}

	@UiHandler("cameras1CBox")
	void onCameras1CBoxChange(ChangeEvent event) {
		final String cam = cameras1CBox.getValue(cameras1CBox.getSelectedIndex());
		loginService.verificaPermissaoAcesso( usuarioLogin, cam, new AsyncCallback<Boolean>() {

			public void onSuccess(Boolean ok) {
				video1Panel.clear();
				String comando = new String();
				comando = getCameraComando( cam );
				HTML h = new HTML(urlVideo(comando).toString());
				video1Panel.add(h);
			}

			public void onFailure(Throwable erro) {
				showErroLogin(erro.getMessage());
				video1Panel.clear();
				video2Panel.clear();
			}

		});
	}

	@UiHandler("cameras2CBox")
	void onCameras2CBoxChange(ChangeEvent event) {
		final String cam = cameras2CBox.getValue(cameras2CBox.getSelectedIndex());
		loginService.verificaPermissaoAcesso( usuarioLogin, cam, new AsyncCallback<Boolean>() {

			public void onSuccess(Boolean ok) {
				video2Panel.clear();
				String comando = new String();
				comando = getCameraComando( cam );
				HTML h = new HTML(urlVideo(comando).toString());
				video2Panel.add(h);
			}

			public void onFailure(Throwable erro) {
				showErroLogin(erro.getMessage());
				video1Panel.clear();
				video2Panel.clear();
			}

		});

	}

	
	private void iniciaChecagemDoTempos(){

		if (usuarioLogin.getPeriodoInicio()!=null && usuarioLogin.getPeriodoFim()!=null){

			Timer timer = new Timer() {
				@Override
				public void run() {
					loginService.verificaPermissaoAcesso( usuarioLogin, "CHECAGEM", new AsyncCallback<Boolean>() {

						public void onSuccess(Boolean ok) {
						}

						public void onFailure(Throwable erro) {
							showErroLogin(erro.getMessage());
							video1Panel.clear();
							video2Panel.clear();
						}

					});
					
				}
			};

			// --- Checa o tempo e intervalo a cada 5min
			timer.scheduleRepeating(5*60*1000);
		}
	}
	
	
	private String getCameraComando( String camera ){

		for (Camera c : usuarioLogin.getCameras()) {
			if (c.getNome().equals(camera)){
				return c.getComando();
			}
		}
		
		return "";
	}
	
	private void populaListCameras(){
		cameras1CBox.clear();
		cameras1CBox.addItem("");
		for (Camera c : usuarioLogin.getCameras()) {
			cameras1CBox.addItem(c.getNome());
		}

		cameras2CBox.clear();
		cameras2CBox.addItem("");
		for (Camera c : usuarioLogin.getCameras()) {
			cameras2CBox.addItem(c.getNome());
		}
	}

//	private void drawVideo() {
//
//		HTML h = new HTML(urlVideo("bercarui1").toString());
//		//	    h.getElement().setId("mediaspace");
//		//	    h.getElement().getStyle().setZIndex(9999);
//		video2Panel.add(h);
//
//
//	}


	private StringBuffer urlVideo( String comandoParam ){
		StringBuffer url = new StringBuffer();

		StringBuffer comando = new StringBuffer();
		
//		comando = "netstreambasepath=http://38.96.175.106/"+camera+".stream&image=&backcolor=000000&frontcolor=000000&lightcolor=cc9900&screencolor=000000&skin=glow.zip&streamer=rtmp://109.123.114.180/IPCAM/&autostart=true&stretching=exactfit&controlbar.position=over";

		comando.append(comandoParam);
		comando.append("id=mediaspace&");
		comando.append("image=&");
		comando.append("backcolor=000000&");
		comando.append("frontcolor=000000&");
		comando.append("lightcolor=cc9900&");
		comando.append("screencolor=000000&");
		comando.append("skin=glow.zip&");
		comando.append("autostart=true&");
		comando.append("stretching=exactfit&");
		comando.append("controlbar.position=over");
		
		url.append("<div id='mediaspace'>");
		url.append("<embed id='mediaspace' width='320' height='240' ");
		url.append("flashvars='"+comando+"' ");
		url.append("wmode='opaque' ");
		url.append("allowscriptaccess='always' ");
		url.append("allowfullscreen='true' ");
		url.append("quality='high' ");
		url.append("name='mediaspace' ");
		url.append("style='undefined' ");
		url.append("src='http://player.longtailvideo.com/player.swf' ");
		url.append("type='application/x-shockwave-flash'>");
		url.append("</div>");

		return url;
	}

	public AcessoCam getUsuarioLogin() {
		return usuarioLogin;
	}

	public void setUsuarioLogin(AcessoCam usuarioLogin) {
		this.usuarioLogin = usuarioLogin;
	}

	private void showErroLogin(String msg) {
		msgErroLabel.setText(msg);
	}

	//============================================================


	//	url.append("<div id='mediaspace'>");
	//	url.append("<embed id='mediaspace' width='320' height='240' ");
	//	url.append("flashvars='file=camera.stream&streamer=rtmp://streaming12.sitehosting.com.br/aconchegohotelescola&autostart=true' ");
	//	url.append("wmode='opaque' ");
	//	url.append("allowscriptaccess='always' ");
	//	url.append("allowfullscreen='true' ");
	//	url.append("quality='high' ");
	//	url.append("name='mediaspace' ");
	//	url.append("style='undefined' ");
	//	url.append("src='http://player.longtailvideo.com/player.swf' ");
	//	url.append("type='application/x-shockwave-flash'>");
	//	url.append("</div>");


	//	private native void teste() /*-{
	//		var so = new $wnd.SWFObject('http://player.longtailvideo.com/player.swf','mpl','320','240','9');
	//		so.addParam('allowfullscreen','true');
	//		so.addParam('allowscriptaccess','always');
	//		so.addParam('wmode','opaque');
	//		so.addVariable('file','camera.stream');
	//		so.addVariable('streamer','rtmp://streaming12.sitehosting.com.br/aconchegohotelescola');
	//		so.addVariable('autostart','true');
	//		so.write('mediaspace');
	//    }-*/;
	//	@UiHandler("sairButton")
	//	void onSairButtonClick(ClickEvent event) {
	//	}

	//	private void drawTwitter() {
	//	    //<a href="http://twitter.com/Gawkat" class="twitter-follow-button" data-show-count="false">Follow @Gawkat</a>
	//	    //<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
	//	    
	//	    String s = "<a href=\"http://twitter.com/Gawkat\" class=\"twitter-follow-button\" data-show-count=\"false\">Follow @Gawkat</a>";
	//	    HTML h = new HTML(s);
	//	    videoPanel.add(h);
	//	    
	//	    Document doc = Document.get();
	//	    ScriptElement script = doc.createScriptElement();
	//	    script.setSrc("http://platform.twitter.com/widgets.js");
	//	    script.setType("text/javascript");
	//	    script.setLang("javascript");
	//	    doc.getBody().appendChild(script);
	//	  }





	//	HTMLPanel html = new HTMLPanel(urlVideo().toString());
	//	html.setWidth("350px");
	//	html.setHeight("250px");
	//	video.add(html);


	//	video.getElement().setId("mediaspace");
	//	video.getElement().setInnerSafeHtml(urlVideo().toString());
	//	video.getElement().setInnerText(urlVideo().toString());
	//	videoPanel.getElement().setInnerHTML(urlVideo().toString());
	//	videoPanel.setWidth("400px");
	//	videoPanel.setHeight("400px");
	//	videoViewPanel.add(videoPanel);

	//	videoPanel.getElement().setId("mediaspace");
	//	videoPanel.getElement().setInnerHTML(urlVideo().toString());
	//	teste();

	//	SWFWidget swfWidget = new SWFWidget("'http://player.longtailvideo.com/player.swf'", 320, 240);
	//	swfWidget.addParam("allowfullscreen","true");
	//	swfWidget.addParam("allowscriptaccess","always");
	//	swfWidget.addParam("wmode","opaque");
	//	swfWidget.addFlashVar("file","camera.stream");
	//	swfWidget.addFlashVar("streamer","rtmp://streaming12.sitehosting.com.br/aconchegohotelescola");
	//	swfWidget.addFlashVar("autostart","true");
	//	swfWidget.addAttribute("id", "swfDivID_0");

	//	video.add(swfWidget);

	//	ScriptInjector.fromString(urlVideo().toString()).inject();
	//	ScriptInjector.fromUrl("http://player.longtailvideo.com/swfobject.js").setCallback(new Callback<Void, Exception>() {
	//
	//		public void onSuccess(Void arg0) {
	//			Window.alert("Script Ok");
	//		}
	//		
	//		public void onFailure(Exception arg0) {
	//			Window.alert("Script Falhou");
	//		}
	//		
	//	}).inject();


	//    drawTwitter();


}
